/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcMsgActivity.java
 *   @Date: 19-1-30 上午11:11
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.adapter.OtcMsgAdapter;
import io.bhex.app.otc.listener.OtcMsgItemClickListener;
import io.bhex.app.otc.presenter.OtcMsgPresenter;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.FileTools;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.crop.ImgPickHandler;
import io.bhex.baselib.utils.crop.ImgPickHelper;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.otc.bean.OtcMessageResponse;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;
import io.bhex.sdk.otc.bean.OtcUploadImgResponse;
import pub.devrel.easypermissions.EasyPermissions;

public class OtcMsgActivity extends BaseActivity<OtcMsgPresenter,OtcMsgPresenter.OtcMsgUI> implements OtcMsgPresenter.OtcMsgUI, View.OnClickListener, TextWatcher,EasyPermissions.PermissionCallbacks {
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x0;
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 0x2;
    private static final int MESSAGE_TYPE_TXT = 1;  //文字
    private static final int MESSAGE_TYPE_IMG = 2;  //图片
    private TopBar topBar;
    private ImageView btnSend;
    private EditText msgInput;
    private boolean isSendMsg=false;
    private AlertView selectPhotoAlert;
    private String[] selectPhotoWayArray;
    private SmartRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private OtcMsgAdapter adapter;
    private OtcOrderInfoResponse currentOrderInfo;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_message_layout;
    }

    @Override
    protected OtcMsgPresenter createPresenter() {
        return new OtcMsgPresenter();
    }

    @Override
    protected OtcMsgPresenter.OtcMsgUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void initView() {
        super.initView();

        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightImg(R.mipmap.icon_call);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OtcOrderInfoResponse orderInfo = getPresenter().getOrderInfo();
                if (orderInfo != null) {
                    int status = orderInfo.getStatus();
                    if (status==20||status==30) {
                        //申诉状态下
                        String appealLastSeconds = orderInfo.getAppealLastSeconds();
                        if (!TextUtils.isEmpty(appealLastSeconds)) {
                            if (Long.valueOf(appealLastSeconds)>0) {
                                ToastUtils.showShort(getString(R.string.string_tip_pay_completed_view_contact));
                            }else{
                                showCallDialog(orderInfo.getTargetConnectInfomation());
                            }
                        }else{
                            showCallDialog(orderInfo.getTargetConnectInfomation());
                        }
                    }else{
                        ToastUtils.showShort(getString(R.string.string_tip_pay_completed_view_contact));
                    }
                }
            }
        });

        btnSend = viewFinder.find(R.id.attachments);
        msgInput = viewFinder.find(R.id.msgInput);
        msgInput.addTextChangedListener(this);
        selectPhotoWayArray = new String[]{getString(R.string.string_take_photo),getString(R.string.string_gallery)};

        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        recyclerView = viewFinder.find(R.id.recyclerView);

    }

    @Override
    public void showOrderInfo(OtcOrderInfoResponse orderInfo) {
        if (orderInfo != null) {
            currentOrderInfo = orderInfo;
            topBar.setTitle(orderInfo.getTargetNickName()+"("+orderInfo.getRecentOrderNum()+"/"+orderInfo.getRecentExecuteRate()+"%）");
            if (orderInfo != null) {
                int status = orderInfo.getStatus();
                //撤销、完全成交状态下不可发送消息
                if (status == 40 || status == 50) {
                    btnSend.setEnabled(false);
                    msgInput.setEnabled(false);
                }else{
                    btnSend.setEnabled(true);
                    msgInput.setEnabled(true);
                }
            }
        }
    }

    /**
     * 联系电话弹框
     * @param targetConnectInfomation
     */
    private void showCallDialog(final String targetConnectInfomation) {
        if (TextUtils.isEmpty(targetConnectInfomation)) {
            return;
        }
        DialogUtils.showDialogOneBtn(this,"",targetConnectInfomation,getString(R.string.string_sure),true,new DialogUtils.OnButtonEventListener(){
            @Override
            public void onConfirm() {
                IntentUtils.callDialPhone(OtcMsgActivity.this,targetConnectInfomation);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.attachments).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.attachments:
                if (isSendMsg) {
                    //发送消息
                    String msg = msgInput.getText().toString();
                    if (TextUtils.isEmpty(msg)) {
                        ToastUtils.showShort(getString(R.string.string_input_msg));
                        return;
                    }
                    getPresenter().sendMessage(msg,MESSAGE_TYPE_TXT);
                }else{
                    //上传附件
                    showSelectPhoto();
                }
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String msg = s.toString();
        if (TextUtils.isEmpty(msg)) {
            isSendMsg = false;
            btnSend.setImageResource(R.drawable.btn_attachment);
        }else{
            isSendMsg = true;
            btnSend.setImageResource(R.drawable.btn_send);
        }
    }

    @Override
    public void sendMsgSuccess() {
        msgInput.setText("");
    }

    @Override
    public void showMessageList(List<OtcMessageResponse.MessageBean> data) {
        if (data != null) {
            if (currentOrderInfo != null) {
                OtcMessageResponse.MessageBean messageBean = data.get(data.size() - 1);
                String id = messageBean.getId();
                SPEx.setMsgId(currentOrderInfo.getId(),id);
            }
        }
        if (adapter == null) {
            adapter = new OtcMsgAdapter(this,currentOrderInfo,data,new OtcMsgItemClickListener(){
                @Override
                public void uploadProof(View view, OtcOrderInfoResponse mOrderInfo) {
                    // 上传证明
//                    if (view.getId()==R.id.uploadProof) {
//                        IntentUtils.goOtcUploadProof(OtcMsgActivity.this,mOrderInfo);
//                    }
                }
            });
            adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this,recyclerView);
            adapter.setEnableLoadMore(false);

            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
//        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));

            recyclerView.setAdapter(adapter);
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId()==R.id.uploadProof) {
                        List<OtcMessageResponse.MessageBean> dataList = adapter.getData();
                        if (dataList != null) {
                        }
                        // 上传证明
                        IntentUtils.goOtcUploadProof(OtcMsgActivity.this,getPresenter().getOrderInfo());
                    }else if(view.getId() == R.id.content){
                        TextView contentTv = (TextView)view.findViewById(R.id.content);
                        String content = contentTv.getText().toString();
                        CommonUtil.copyText(OtcMsgActivity.this,content);
                    }
                }
            });
        } else {
            adapter.setNewData(data);
        }
        scrollBottom();
    }

    private void scrollBottom() {
        if (adapter != null) {
            if (adapter.getItemCount()>1) {
                recyclerView.scrollToPosition(adapter.getItemCount()-1);
            }
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImgPickHelper.getInstance().handleResult(this, requestCode, resultCode, data);
    }

    /**
     * 选择图片
     */
    private void showSelectPhoto() {
        if(selectPhotoAlert != null && selectPhotoAlert.isShowing())
            return;
        selectPhotoAlert = new AlertView(null, null, getString(R.string.string_cancel), null, selectPhotoWayArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position==0){
                    //拍照
                    startSelectImage(true);
                }else{
                    //从相册选择
                    startSelectImage(false);
                }
            }
        });
        selectPhotoAlert.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
            }
        });
        selectPhotoAlert.show();
    }

    private void startSelectImage(boolean bCamera){
//        ImgPickHelper.getInstance().clearCachedCropFile(AuthenticateSubmitActivity.this);
        ImgPickHelper.getInstance().registeHandler(new ImgPickHandler() {

            @Override
            public void onSuccess(Uri uri) {
                uploadImage(uri);
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFailed(String message) {


            }
        });
        ImgPickHelper.getInstance().needCrop(false);
        if (bCamera) {
            String[] perms = {Manifest.permission.CAMERA};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), CAMERA_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goCamera(this);
            }

            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goCamera(getActivity());
            }*/

        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goGallery(this);
            }
            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goGallery(getActivity());
            }*/
        }

    }

    private void uploadImage(final Uri fromUri) {
        if(fromUri == null)
            return;
        if (FileTools.fileIsExists(fromUri.getPath())) {
            //if(mJSImageCallback != null){
            getPresenter().uploadImage(fromUri.getPath(), new SimpleResponseListener<OtcUploadImgResponse>() {

                @Override
                public void onBefore() {
                    super.onBefore();
                    getUI().showProgressDialog("", getString(R.string.string_uploading));
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    getUI().dismissProgressDialog();
                }

                @Override
                public void onSuccess(OtcUploadImgResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, true)) {
                            String photoUrl = response.getUrl();
//                            Glide.with(OtcMsgActivity.this)
//                                    .load(fromUri.getPath())
//                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
//                                    .skipMemoryCache(true)
//                                    .into(photoImg1);
                        getPresenter().sendMessage(photoUrl,MESSAGE_TYPE_IMG);

//                        ToastUtils.showLong(OtcMsgActivity.this, getString(R.string.string_upload_success));

                    }
                }

                @Override
                public void onError(Throwable error) {
//                    ToastUtils.showLong(OtcMsgActivity.this,getString(R.string.string_upload_failed));
                }

            });
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        requestCodeQRCodePermissions();
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE){
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(this);
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(this);
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ImgPickHelper.getInstance().unregistHandler();
    }
}
